<template>
  <TablePage>
    <template #top>
      <SearchForm title="排班计划" :select-data="selectData" @search="search">
        <template #extraButtons>
          <a-button :loading="downloading" class="mr-2" @click="downloadTemplate">
            <DownloadOutlined />
            下载计划模板
          </a-button>
          <a-upload
            v-model:file-list="fileList"
            :show-upload-list="false"
            :max-count="1"
            method="put"
            name="file"
            :action="env.baseUrl + teamApi.uploadTemplate"
            :headers="headers"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <a-button :loading="uploading" type="primary">
              <upload-outlined></upload-outlined>
              上传排班计划
            </a-button>
          </a-upload>
        </template>
      </SearchForm>
    </template>
    <a-skeleton v-if="loading" :paragraph="{ rows: 5 }" active />
    <SlTable v-else :columns="columns" :data-source="data" bordered>
      <template #bodyCell="{ column, record, index }">
        <div
          v-if="column.dataIndex !== 'name'"
          class="relative z-10"
          style="margin: -16px; padding: 16px"
          @click="clickTollTd(column, index)"
        >
          <template v-if="curEditingObj[column.dataIndex + '-' + index]">
            <a-select
              v-model:value="record[column.dataIndex + ':tollBoothId']"
              :options="tollSelData"
              @change="tollSelChange($event, column, record, index)"
            >
            </a-select>
            <CloseCircleOutlined class="ml-2 !text-gray-600 cursor-pointer" @click.stop="curEditingObj = {}" />
          </template>
          <span v-else>{{ record[column.dataIndex + ":tollBoothNo"] || "--" }}</span>
        </div>
      </template>
    </SlTable>
  </TablePage>
</template>
<script lang="ts" setup>
import { message } from "ant-design-vue";
import type { TableColumnsType, UploadChangeParam } from "ant-design-vue";
import { CloseCircleOutlined, UploadOutlined, DownloadOutlined } from "@ant-design/icons-vue";
import { computed, onMounted, reactive, ref, shallowRef, watch } from "vue";
import { useI18n } from "/@/locales/useI18n";

import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import { LabelSelectType, SelectItem } from "/@/types/components";
import type { ColumnGroupType } from "ant-design-vue/lib/table";
import type { DefaultOptionType } from "ant-design-vue/lib/select";
import { Api } from "/@/api/main/civilizedService";
import { useCURD } from "/@/hooks/useCURD";
import { TollBoothItem, TollCollectorItem } from "/@/api/main/civilizedService/models";
import { Api as teamApi, delPlan, getPlan, setPlan, updatePlan } from "/@/api/main/teamManage";
import { PlanType, TeamItem } from "/@/api/main/teamManage/models";
import { exportReq } from "/@/api/common";
import { downloadFile } from "/@/utils/common";
import { getAuthHeaderInfo } from "/@/api/req";
import env from "/@/base/env";

const { t } = useI18n();

//所有收费岗亭数据
const { tableData: tollBoothData, reloadTable: tollBoothReload } = useCURD<TollBoothItem>({
  pageSize: 9999,
  getPageUrl: Api.tollBooths,
  loadOnMounted: false,
});
//所有收费员数据
const { tableData: tollCollectorData, reloadTable: tollCollectorReload } = useCURD<TollCollectorItem>({
  pageSize: 9999,
  getPageUrl: Api.tollCollectorsPage,
  loadOnMounted: false,
});
//所有班组数据
const { tableData: teamData, reloadTable: teamReload } = useCURD<TeamItem>({
  getPageUrl: teamApi.teamsPage,
  pageSize: 9999,
  loadOnMounted: false,
});
const loading = ref(true);
onMounted(() => {
  Promise.all([tollBoothReload(), tollCollectorReload(), teamReload()])
    .then(() => {
      loading.value = false;
      const options: DefaultOptionType[] = [{ label: "无", value: -1 }];
      tollSelData.value = options.concat(
        tollBoothData.value.map((el) => ({
          label: el.tollBoothNo,
          value: el.id,
        }))
      );
      createColumns(dayjs());
    })
    .catch(() => {
      //...
    });
});

const selectData = ref<SelectItem[]>([
  {
    label: "选择周",
    key: "weekTime",
    selectType: LabelSelectType.datePicker,
    props: {
      picker: "week",
    },
    value: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  },
]);
function search(model) {
  if (loading.value) return;
  if (model.weekTime) {
    createColumns(dayjs(model.weekTime));
  }
}

let curStartDate = "";
let curEndDate = "";
function createColumns(dayjsIns: Dayjs) {
  let start = dayjsIns.startOf("week");
  let end = dayjsIns.endOf("week");
  curStartDate = start.format("YYYY-MM-DD");
  curEndDate = end.format("YYYY-MM-DD");
  end = end.add(1, "day");
  const newColumns: TableColumnsType = [
    {
      title: "人员",
      dataIndex: "name",
      fixed: true,
    },
  ];
  while (!start.isSame(end, "day")) {
    let title = start.format("MM-DD");
    const chColumns: TableColumnsType = [];
    teamData.value.forEach((t) => {
      chColumns.push({
        title: t.teamName?.charAt(0),
        dataIndex: start.format("YYYY-MM-DD") + ":" + t.id,
      });
    });
    newColumns.push({
      title,
      children: chColumns,
    });
    start = start.add(1, "day");
  }
  columns.value = newColumns;
  const newData: any = [];
  tollCollectorData.value.forEach((el) => {
    const obj: any = {
      name: el.tollCollector,
    };
    newColumns.forEach((col: any) => {
      col.children?.forEach((el) => {
        obj[el.dataIndex] = null;
        obj[el.dataIndex + ":tollBoothId"] = -1;
        obj[el.dataIndex + ":tollBoothNo"] = "--";
      });
    });
    newData.push(obj);
  });
  data.value = newData;
  reloadPlanData();
}
async function reloadPlanData() {
  const planData = await getPlan({
    startDate: curStartDate,
    endDate: curEndDate,
  });
  if (planData) {
    //先重置数据
    planData.forEach((item) => {
      item.data.forEach((subItem) => {
        const tollCollectorIndex = tollCollectorData.value.findIndex((el) => el.id === subItem.tollCollectorId);
        if (tollCollectorIndex >= 0) {
          const row = data.value[tollCollectorIndex];
          row[subItem.planDate + ":" + subItem.teamId + ":tollBoothId"] = subItem.tollBoothId;
          const targetTollBooth = tollBoothData.value.find((el) => el.id === subItem.tollBoothId);
          row[subItem.planDate + ":" + subItem.teamId + ":tollBoothNo"] = targetTollBooth
            ? targetTollBooth.tollBoothNo
            : "";
          row[subItem.planDate + ":" + subItem.teamId + ":planId"] = subItem.id;
        }
      });
    });
  }
}
const columns = ref<TableColumnsType>([]);
const data = ref<any>([]);

const tollSelData = ref<DefaultOptionType[]>([]);

const curEditingObj: any = ref({});
function clickTollTd(column, index) {
  curEditingObj.value = {
    [column.dataIndex + "-" + index]: 1,
  };
}
//开始排班
async function tollSelChange(tollBoothId, column, record, index) {
  const planId = record[column.dataIndex + ":planId"];
  if (tollBoothId === -1) {
    if (planId) {
      const re = await delPlan(+planId);
      if (re) {
        message.success("设置成功");
        record[column.dataIndex + ":tollBoothId"] = -1;
        record[column.dataIndex + ":tollBoothNo"] = "";
        record[column.dataIndex + ":planId"] = "";
        reloadPlanData();
      }
    }
    curEditingObj.value = {};
    return;
  }
  const dataIndex = column.dataIndex;
  const arr = dataIndex.split(":");
  let re: any = null;
  if (planId) {
    re = await updatePlan({
      id: +planId,
      teamId: +arr[1],
      planDate: arr[0],
      planType: PlanType.WORKING,
      tollBoothId,
      tollCollectorId: tollCollectorData.value[index].id as number,
    });
  } else {
    re = await setPlan({
      teamId: +arr[1],
      planDate: arr[0],
      planType: PlanType.WORKING,
      tollBoothId,
      tollCollectorId: tollCollectorData.value[index].id as number,
    });
  }

  if (re) {
    message.success("设置成功");
    curEditingObj.value = {};
    reloadPlanData();
  }
}

const downloading = ref(false);
async function downloadTemplate() {
  if (!curStartDate || !curEndDate) return;
  downloading.value = true;
  const blobData = await exportReq(teamApi.template, {
    startDate: curStartDate,
    endDate: curEndDate,
  });
  downloading.value = false;
  if (blobData) {
    downloadFile(blobData, `计划模板(${curStartDate}至${curEndDate})`);
  }
}
const fileList = ref<any>([]);
const headers = ref<any>({});
function beforeUpload() {
  if (uploading.value) return false;
  headers.value = getAuthHeaderInfo();
  uploading.value = true;
  return true;
}
const uploading = ref(false);
function handleChange(info: UploadChangeParam) {
  if (info.file.status === "done") {
    message.success(`${info.file.name}上传成功`);
    uploading.value = false;
    reloadPlanData();
  } else if (info.file.status === "error") {
    message.error(`${info.file.name}上传失败，请稍候再试`);
    uploading.value = false;
  }
}
</script>
<style lang="less"></style>
